<!--
  * 配送单
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <a-col :span="{ sm: 7, md: 6 }">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="配送状态" class="smart-margin-bottom0">
            <EnumSelect enum-name="UNSETYLED_TY_ENUM" v-model:value="queryForm.status" placeholder="配送状态" @submit="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="订单类型" class="smart-margin-bottom0">
            <EnumSelect enum-name="ORDER_STATRS_ENUM" v-model:value="queryForm.type" placeholder="订单类型" @submit="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="司机" class="smart-margin-bottom0">
            <Select name="Driver" v-model:value="queryForm.driver_id" placeholder="请选择" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQueryData" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <SearchFormCollapse v-model="expand" />
          </a-button-group>
        </a-col>
        <template v-if="expand">
          <a-col :span="4">
            <a-form-item label="协送员" class="smart-margin-bottom0">
              <Select name="Driver" v-model:value="queryForm.escort_driver_id" placeholder="请选择" @input-enter="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="业务员" class="smart-margin-bottom0">
              <Select name="Salesman" v-model:value="salesman_id" placeholder="请选择" @input-enter="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="门店名称" class="smart-margin-bottom0">
              <Select name="Store" v-model:value="store_id" placeholder="门店" @input-enter="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="出库仓库" name="warehouse_id" class="smart-margin-bottom0">
              <Select name="Warehouse" v-model:value="queryForm.warehouse_id" :fetch-params="selectFetchParams.warehouse" placeholder="请选择仓库" @input-enter="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="单据编号" class="smart-margin-bottom0">
              <a-input v-model:value.trim="queryForm.no" placeholder="单据编号" allow-clear />
            </a-form-item>
          </a-col>
        </template>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="onExport" type="primary" v-privilege="'goods:exportGoods'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.title === '源订单号'">
            <template v-if="record.is_abnormal === 1">
              <CopyText :text="text">
                <a @click="detail(record)">{{ text }}</a>
              </CopyText>
            </template>
            <template v-else>
              <CopyText :text="text" class="is_abnormal">
                <a-badge count="异常" color="red" :offset="[18, -2]">
                  <a @click="detail(record)">{{ text }}</a>
                </a-badge>
              </CopyText>
            </template>
          </template>
          <template v-if="column.dataIndex === 'type'">
            <a-tag :color="TagColor[text]">{{ getDescByValue('ORDER_STATRS_ENUM', Number(text)) }}</a-tag>
          </template>
          <template v-if="record?.sign && column.dataIndex === 'payment_type'">
            <a-tag :color="TagColor[record?.sign?.payment_type]">{{ getDescByValue('RECEIVE_TYPE_ENUM', Number(record?.sign?.payment_type)) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'payment_status'">
            <a-tag :color="TagColor[record.sign ? 1 : 2]">{{ record.sign ? '已结算' : '未结算' }}</a-tag>
          </template>
          <template v-if="['total_volume', 'total_weight'].includes(column.dataIndex)">
            {{ text?.toFixed(2) }}
          </template>
          <template v-if="column.dataIndex === 'is_load'">
            <a-tag :color="text === 1 && !record?.driver_id ? 'error' : 'success'">{{ text === 1 && !record?.driver_id ? '未分配' : '已分配' }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'order_sign_number'">
            <span :style="{ color: record.status == 3 && record?.order_number !== record?.order_sign_number ? 'red' : 'inherit' }">{{ text }}</span>
          </template>
          <template v-if="column.dataIndex === 'warehouse_name'">
            <span
              >{{ record.related?.warehouse?.name }}<span v-if="record.related?.warehouse?.attribute_type">({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', record.related?.warehouse?.attribute_type) }})</span>
            </span>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="TagColor[text]">{{ getDescByValue('UNSETYLED_TY_ENUM', Number(text)) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c" v-privilege="'goods:update'">详情</a-button>
            </div>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <template v-for="item in columns">
                <template v-if="item.title === '源订单号'">
                  <a-table-summary-cell>总计</a-table-summary-cell>
                </template>
                <template v-if="item.dataIndex === 'order_total_price'">
                  <a-table-summary-cell>
                    <a-typography-text type="danger">{{ total_amount.all_order_total_price }}</a-typography-text>
                  </a-table-summary-cell>
                </template>
                <template v-else>
                  <a-table-summary-cell />
                </template>
              </template>
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
    <!---------- 详情 begin ----------->
    <BookingDetailsModal ref="detailRef" />
    <!---------- 详情 end ----------->
  </a-card>
</template>
<script setup lang="ts">
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import BookingDetailsModal from './components/booking-details-modal.vue'
import { deliveryApi } from '@/api/business/logistics/booking-api'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import TableOperator from '@/components/support/table-operator/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import Select from '@/components/business/select/index.vue'
import SearchFormCollapse from '@/components/support/search-form-collapse/index.vue'
import _ from 'lodash'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import { WAREHOUSE_TYPE, WAREHOUSE_ATTRIBUTE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'

const appConfigStore = useAppConfigStore()
const { getDescByValue } = useEnums()

// ----------------------------- tag状态 -----------------------------
enum TagColor {
  'error' = 1,
  'orange',
  'success',
  'processing',
  'warning',
  'default'
}
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY, expand } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '源订单号',
    dataIndex: ['related', 'no'],
    width: appConfigStore.$state.compactFlag ? 170 : 190
  },
  {
    title: '订单类型',
    dataIndex: 'type'
  },
  {
    title: '创建时间',
    dataIndex: 'create_time'
  },
  {
    title: '出库仓库',
    dataIndex: 'warehouse_name'
  },
  {
    title: '门店名称',
    dataIndex: ['related', 'store', 'store_name']
  },
  {
    title: '配送状态',
    dataIndex: 'status'
  },
  {
    title: '业务员',
    dataIndex: ['related', 'salesman', 'rename']
  },
  {
    title: '司机',
    dataIndex: ['driver', 'name']
  },
  {
    title: '协送员',
    dataIndex: ['escort', 'name']
  },
  {
    title: '配送数量',
    dataIndex: 'order_number'
  },
  {
    title: '配送金额',
    dataIndex: 'order_total_price'
  },
  {
    title: '签收数量',
    dataIndex: 'order_sign_number'
  },
  {
    title: '签收时间',
    dataIndex: ['sign', 'create_time']
  },
  {
    title: '结算方式',
    dataIndex: ['related', 'payment_type_text']
  },
  {
    title: '结算状态',
    dataIndex: 'payment_status'
  },
  {
    title: '签收金额',
    dataIndex: 'order_sign_total_price'
  },
  {
    title: '结算时间',
    dataIndex: ['settlement', 'settlement_time']
  },
  {
    title: '配送体积(m³)',
    dataIndex: 'total_volume'
  },
  {
    title: '配送重量(kg)',
    dataIndex: 'total_weight'
  },
  {
    title: '片区',
    dataIndex: ['related', 'store', 'region', 'name']
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 80
  }
])
// ---------------------------- 查询数据表单和方法 ----------------------------
const salesman_id = ref(null)
const store_id = ref(null)
const total_amount = ref({
  all_order_total_price: 0
})
const { queryForm, queryFormOp, tableData, tableLoading, total, resetQuery, onSearch, queryData } = useQuery({
  fetchDataApi: async (params) => {
    const data = {
      ...params,
      salesman_id: salesman_id.value,
      store_id: store_id.value
    }
    const res = await deliveryApi.queryDeliveryList(data)
    total_amount.value = _.pick(res.data, Object.keys(total_amount.value))
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {
    no: '',
    driver_id: undefined,
    escort_driver_id: undefined,
    create_time: DEFAULT_TIME_RANGE.value,
    type: null,
    status: null,
    is_load: undefined
  },
  queryFormOp: {
    no: QUERY_FORM_OP['模糊查询'],
    driver_id: QUERY_FORM_OP['全等查询'],
    escort_driver_id: QUERY_FORM_OP['全等查询'],
    create_time: QUERY_FORM_OP['范围查询'],
    type: QUERY_FORM_OP['全等查询'],
    status: QUERY_FORM_OP['全等查询'],
    is_load: QUERY_FORM_OP['全等查询']
  }
})

onActivated(queryData)

// Select查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value,
      attribute_type: [WAREHOUSE_ATTRIBUTE_TYPE.WAREHOUSE.value, WAREHOUSE_ATTRIBUTE_TYPE.TEMPORARY.value]
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询'],
      attribute_type: QUERY_FORM_OP['IN查询'] // 正库/处理库
    },
    fields: 'id,name'
  }
}

const resetQueryData = () => {
  salesman_id.value = null
  store_id.value = null
  resetQuery()
}

// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = (goodsData) => {
  detailRef.value.showDrawer(goodsData)
}

// ---------------------------- 批量 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([])

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys
}
// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const { page, limit, ...filter } = queryForm.value
  const data = {
    filter: JSON.stringify(filter),
    op: JSON.stringify(queryFormOp),
    salesman_id: salesman_id.value,
    store_id: store_id.value
  }
  deliveryApi.exportXlsx(data)
}
</script>
<style scoped lang="less">
:deep(.ant-badge .ant-badge-count) {
  height: 16px;
  line-height: 16px;
  font-size: 10px;
}
</style>
